<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import {useGetIndexOrderInfoApi, useStartTaskApi, useInspectionApi, useEndTaskApi,useCancelTaskApi} from "@/apis/order"
import { computed, reactive, ref } from 'vue';
import constant from "@/utils/constant"
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const orderInfo = ref<any>({
	
})
const waybill = ref<any>([])
const status = ref(false)
const loading = ref(true)
const showStar = ref(false)
const showEnd = ref(false)
const inspectNum = ref(0)
const popupShow = ref(false)
const showCancel = ref(false)
let id: any
onLoad((e)=>{
	id = e?.id
	init()
})

function init(){
	useGetIndexOrderInfoApi(id).then(res=>{
		const {task, project, car, billList, ongoing, check} = res
		console.log(ongoing)
		status.value = ongoing
		orderInfo.value = Object.assign({}, project, car, task)
		waybill.value = billList
		inspectNum.value = check
		loading.value = false
		form.waybillId = billList?.find((item: any) => item.state === 1)?.id
		form.type = task.acceptType === 3 && check === 1? 2 : 1
	})
}
const situationArr = [0, 1, 1, 2]
const useEndTask = computed(()=>{
	return situationArr[orderInfo.value.acceptType] === inspectNum.value
})

const form = reactive({
	waybillId: undefined,
	type: 1,
	state: 1,
	remark: "",
	pic: ""
})
const formRef = ref()
const rules = {
	pic: {required: true,message: '必须上传货物图片',trigger: ['change','blur']},
}
const image = reactive<any>([])

function deletePic(event){
  image.splice(event.index, 1);
  form.pic = ""
}
	
async function afterRead(event){
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	const lists: any = [].concat(event.file);
	let fileListLen = image.length;
	lists.forEach((item: any) => {
	image.push({
	    ...item,
	    status: 'uploading',
		message: '上传中',
		});
	});
	for (let i = 0; i < lists.length; i++) {
		const result = await uploadFilePromise(lists[i].url);
		const item = image[fileListLen];
		image.splice(fileListLen, 1, {
			...item,
			status: 'success',
			message: '',
			url: result,
		});
		form.pic = JSON.parse(result as string).data
		fileListLen++;
	}
};

function uploadFilePromise(url){
	return new Promise((resolve) => {
		uni.uploadFile({
			url: constant.uploadUrl, // 仅为示例，非真实的接口地址
			filePath: url,
			name: 'file',
			header: {
				Authorization: userStore.token
			},
			formData: {
			},
			success: (res: any) => {
				setTimeout(() => {
					resolve(res.data);
				}, 1000)
			}
	    });
	});
};

function radioChange(val){
	form.state = val
}

function startTask(){
	useStartTaskApi(id).then(()=>{
		showStar.value = true
	})
}

function endTask(){
	showEnd.value = true
}

function inspection(){
	popupShow.value = true
}

function uploadInspection(){
	console.log(form);
	useInspectionApi(form).then(()=>{
		uni.showToast({
			title: '上传成功',
			icon: 'success',
			duration: 1000
		})
		popupShow.value = false
		loading.value = true
		form.pic = ""
		form.remark = ""
		form.state = 0
		image.splice(0, 1);
		init()
	})
}

function queryWaybill(id){
	uni.navigateTo({
		url: "/pages/order/waybill?id=" + id
	})
}

function assignment(id){
	uni.navigateTo({
		url: "/pages/order/assigntasks?id=" + id
	})
}

function getContent(){
	return "在开始本次任务前，请注意以下事项：\n"+
		"1、请仔细查看任务详情\n"+
		"2、如需装货卸货查验\n"
}

function confirmEnd(){
	showEnd.value = false
	useEndTaskApi(id).then(()=>{
		uni.showToast({
			title: '已结束本次运单',
			icon: 'success',
			duration: 1000
		})
		loading.value = true
		init()
	})
}
function confirmStar(){
	uni.showToast({
		title: '已开始本次运单',
		icon: 'success',
		duration: 1000
	})
	showStar.value = false
	loading.value = true
	init()
}
function cancelTask(){
	// console.log(id);
	useCancelTaskApi(id).then(()=>{
		showCancel.value = false
		uni.showToast({
			title: '已取消本次运单',
			icon: 'success',
			duration: 1000
		})
		loading.value = true
		init()
	})
}
</script>

<template>
	<u-loading-page :loading="loading"/>
	<u-modal :show="showStar" @confirm="confirmStar" title="提示" :content='getContent()'/>
	<u-modal :show="showEnd" @confirm="confirmEnd" title="确认是否验收" :showCancelButton="true" @cancel="showEnd=false"/>
	<u-modal :show="showCancel" @confirm="cancelTask" title="确认是否取消任务" :showCancelButton="true" @cancel="showCancel=false"/>
	<view style="" v-show="!loading" class="page_color">
		<view class="Info_back">
			<view class="task">{{orderInfo.name}}</view>
			<u-line margin="10rpx"/>
			<view class="item"><text>任务编号</text><text>{{orderInfo.id}}</text></view>
			<view class="item"><text>任务名称</text><text>{{orderInfo.name}}</text></view>
			<view class="item"><text>货物名</text><text>{{orderInfo.cargoName}}</text></view>
			<view class="item"><text>起点</text><text>{{orderInfo.loadingAddress}}</text></view>
			<view class="item"><text>终点</text><text>{{orderInfo.unloadingAddress}}</text></view>
			<!-- <view class="item"><text>单趟金额</text><text>{{orderInfo.revenue}}</text></view> -->
			<view class="item">
				<text>装货检查</text>
				<text>{{orderInfo.acceptType === 1 || orderInfo.acceptType === 3? "是" : "否"}}</text>
			</view>
			<view class="item">
				<text>卸货检查</text>
				<text>{{orderInfo.acceptType === 2 || orderInfo.acceptType === 3? "是" : "否"}}</text>
			</view>
			<view class="item"><text>创建时间</text><text>{{orderInfo.createTime}}</text></view>
		</view>
		<view class="">
			<view class="btn">
				<u-button :customStyle="{marginTop: '30rpx'}" v-if="!status && orderInfo.state !== 2 && orderInfo.remainder !== 0" type="primary" @click="startTask" text="开始任务"/>
				<view v-if="status" style="margin-top: 30rpx;" class="a">
					<u-button v-if="!useEndTask" type="primary" @click="inspection" :text="orderInfo.acceptType === 3 && inspectNum === 1?'卸货查验' : '装货查验'" shape="circle"/>
					<u-button v-else type="error" @click="endTask" text="结束任务" shape="circle" :plain="true" />
					<u-button
					type="error" text="取消任务" 
					shape="circle"
					:plain="true" 
					:customStyle="{marginLeft:'10rpx'}"
					@click="showCancel = true"
					/>
				</view>
				<u-button :customStyle="{marginTop: '30rpx'}" v-if="waybill.length" type="success" @click="queryWaybill(orderInfo.id)" :text="`查看运单(${waybill.length})`"/>
				<u-button :customStyle="{marginTop: '30rpx'}" v-if="userStore.user.fleetCaptain===1" type="success" @click="assignment(orderInfo.id)" :plain="true" :text="`分配任务`"/>
			</view>
		</view>
	</view>
	<u-popup :show="popupShow" mode="bottom" @close="popupShow=false" :closeable="true" :customStyle="{padding: '40rpx'}" safeAreaInsetBottom>
	            <u-form :model="form" ref="formRef" :rules="rules" label-position="top">
	            	<u-form-item prop="state" label="核查货物状态" :required="true" label-width="125">
	            		<u-radio-group 
	            		    v-model="form.state"
	            		    placement="row"
							@change="radioChange">
	            			<u-radio label="正常" name="1" :customStyle="{marginRight: '8px'}"/>
	            			<u-radio label="异常" name="2"/>
	            		</u-radio-group>
	            	</u-form-item>
					<u-form-item prop="remark" label="说明">
						<u--textarea v-model="form.remark" placeholder="请说明异常情况,如无异常可不填" autoHeight/>
					</u-form-item>
					<u-form-item prop="pic" label="查验货物图片" label-width="130" :required="true">
						<u-upload
								:fileList="image"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="1"
							/>
					</u-form-item>
				</u-form>
				<up-button type="primary" @click="uploadInspection" text="上传"/>
			</u-popup>
</template>

<style scoped>
	.task{
		margin: 20rpx;
		text-align: center;
		font-size: 40rpx;
	}
	.task::before{
		content: "";
		background-image: url("../../static/img/任务.png");
		display: inline-block;
		background-size: cover;
		width: 40rpx;
		height: 40rpx;
		transform: translateY(9rpx) translateX(-10rpx);
	}
	.a{
		/* width: 500rpx; */
		display: flex;
		justify-content: space-between;
	}
page{
	height: 100%;
}
.Info_back{
	padding: 20rpx;
	background-color: #ffff;
	border-radius: 20rpx;
}
.page_color{
	padding: 10px 10px;
	height: 100%;
	background: linear-gradient(to bottom, #edd9fd 10% ,#d8c6e6 20%, #F8F8F8 100%);
	}
.item{
	display: flex;
	font-size: 28rpx;
}
.item > text{
	display: inline-block;
}
.item > text:first-child{
	min-width: 150rpx;
	margin-right: 50rpx;
	text-align: right;
}
.btn>button{
	margin-top: 15rpx;
}
.accept::after{
	content: "已上传";
	color: rgb(90, 199, 37);
	margin-left: 50rpx;
	opacity: 0;
}
.on{
	opacity: 1;
}

</style>